﻿using System;
using System.Linq;
using System.Data.Linq;
using DR.DBDomainModel;
using DR.Repository.Abstract;
using System.Collections.Generic;

namespace DR.Repository.Concrete.LinqToSql
{
    public class LinqToSqlProjectRepository : LinqToSqlBaseRepository<Project, int>, IProjectRepository
    {
        public LinqToSqlProjectRepository(string connectionString) : base(connectionString)
        {            
        }

        protected override Table<Project> GetDataTable(DataContext dataContext)
        {
            return dataContext.GetTable<Project>();
        }

        protected override System.Linq.Expressions.Expression<Func<Project, bool>> GetIDQuery(int id)
        {
            return r => r.ProjectID == id;
        }

        protected override int GetEntityID(Project entity)
        {
            return entity.ProjectID;
        }

        public IList<Project> SelectAccessibleForDeveloper(int developerID)
        {
            using (DataContext dc = CreateDataContext())
            {
                return dc.GetTable<DeveloperProject>()
                    .Where(r => r.DeveloperID == developerID)
                    .Select(r => r.Project)
                    .ToList();
            }
        }

        public IList<Project> SelectByFilter(string projectName, DateTime? dateLeft, DateTime? dateRight, ISet<int> includeReportStatuses)
        {
            using (DataContext dc = CreateDataContext())
            {
                var project = dc.GetTable<Project>().AsQueryable();

                if (projectName != null && projectName != "")
                {
                    project = project.Where(r => r.Name == projectName);
                }
                if (dateLeft.HasValue)
                {
                    project = project.Where(r => r.DateStart > dateLeft);
                }
                if (dateRight.HasValue)
                {
                    project = project.Where(r => r.DateFinish < dateRight);
                }
                if (includeReportStatuses != null)
                {
                    project = project.Where(r => ((IEnumerable<int>)includeReportStatuses).Contains(r.Status));
                }

                return project.ToList();
            }
        }

    }
}
